package com.platform.wx.mp.config;

import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.google.common.collect.Maps;
import com.platform.entity.MpMsgEntity;
import com.platform.service.MpMsgService;

@Component
public class WxPayConfiguration {
    @Autowired
    private MpMsgService mpMsgService;

    private Map<Integer, WxPayService> wxPayServiceMap = Maps.newHashMap();
    
    public WxPayService getPayService(Integer mpId) {
    	if(wxPayServiceMap.get(mpId) != null) {
    		return wxPayServiceMap.get(mpId);
    	}
    	
    	MpMsgEntity mpMsg = mpMsgService.queryObject(mpId);
    	if(mpMsg.getMchId() == null) {
    		return null;
    	}
    	MpMsgEntity mchMsg = mpMsgService.queryObject(mpMsg.getMchId(),true);
    	if(mchMsg == null) {
    		return null;
    	}
    	
    	WxPayServiceImpl wxPayService = new WxPayServiceImpl();
    	
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(mpMsg.getAppId());//公众号或者小程序等的appid
        payConfig.setMchId(mchMsg.getAppId());//微信支付商户号
        payConfig.setMchKey(mchMsg.getToken());//微信支付商户密钥
//        payConfig.setSubAppId(ResourceUtil.getConfigByName("mp.mchId"));//服务商模式下的子商户公众账号ID
//        payConfig.setSubMchId(ResourceUtil.getConfigByName("mp.mchId"));//服务商模式下的子商户号
        payConfig.setKeyPath(mchMsg.getAesKey());
        // 可以指定是否使用沙箱环境
        payConfig.setUseSandboxEnv(false);
        wxPayService.setConfig(payConfig);
        wxPayServiceMap.put(mpMsg.getId(), wxPayService);
        return wxPayService;
    }

}
